<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-04-09
 * @Time: 23:43
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： OrderBonus.php
 */
namespace app\common\model\zds;

use app\common\model\BuyBill;
use think\Db;
use think\Log;
use think\Model;

/**
 * Class OrderBonus
 * @package app\common\model\zds
 *
 * @property mixed id
 * @property mixed orderid
 * @property mixed billid
 * @property mixed billno
 * @property mixed agencyid
 * @property mixed salesmanid
 * @property mixed customerid
 * @property mixed userid
 * @property mixed order_amount
 * @property mixed agency_bonus_ratio
 * @property mixed agency_bonus_amount
 * @property mixed salesman_bouns_ratio
 * @property mixed salesman_bouns_amount
 * @property mixed create_time
 */
class OrderBonus extends Model {
    protected $table = 'zds_order_bonus';
    protected $pk = 'id';

    /**
     * createBonus
     * 创建销售订单提成记录
     *
     * @author zhengkai
     * @date 2018-04-09
     *
     * @param int $userId 掌乾用户id
     * @param int $billId 掌乾订单id
     * @param string $billOn 掌乾订单号
     * @param int $orderId 销售订单id
     * @param int $agencyId 分销机构id
     * @param int $salesmanId 分销业务员id
     * @param int $customerId 销售客户id
     * @param integer|float $amount 实付订单金额
     * @return bool
     */
    public static function createBonus($orderId, $billId)
    {
        $bill = BuyBill::get($billId);
        $customer = Customer::getSingleCustomer($bill->bill_user);

        $agency = Agency::get($customer->agencyid);
        $salesman = Salesman::get($customer->salesmanid);

        // 业务员提成比例为0时使用机构统一设置的业务员提成比例
        if ($salesman->bonus <= 0) $salesman->bonus = $agency->salesman_bonus;

        $data = [
            'orderid' => $orderId,
            'billid' => $bill->bill_id,
            'billno' => $bill->bill_no,
            'agencyid' => $customer->agencyid,
            'salesmanid' => $customer->salesmanid,
            'customerid' => $customer->id,
            'userid' => $bill->bill_user,
            'order_amount' => $bill->bill_pay_amount,
            'agency_bonus_ratio' => $agency->bonus,
            'agency_bonus_amount' => round(($agency->bonus/100)*$bill->bill_pay_amount, 2),
            'salesman_bouns_ratio' => $salesman->getAttr('bonus'),
            'salesman_bouns_amount' => round(($salesman->bonus/100)*$bill->bill_pay_amount, 2),
            'create_time' => date('Y-m-d H:i:s', time())
        ];

        Db::startTrans();
        try {
            self::create($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("创建销售订单提成记录【error】：{$e->getMessage()}");
            return false;
        }
    }
}